<?php

class User_cartController extends BaseController {

	public function setAction() {
		$goodsData = Request::getParams('goodsData');
		$goodsData = explode(';', $goodsData);
		$updateData = [];
		if ($goodsData) {
			foreach ($goodsData as $goods) {
				$goods = explode(':', $goods);
				if (isset($goods[1]) && isset($goods[0]) && isset($goods[2]) &&
					is_numeric($goods[0]) && is_numeric($goods[1]) && is_numeric($goods[2])) {
					if (!$goodsInfo = self::model('goods')->getOne('goods_id=?', $goods[0])) {
						continue;
					}
					if (!$goodsspecification = self::model('goods_specification')->getOne('specification_id=?', $goods[2])) {
					}
//                    if($goodsInfo['status'] != goodsModel::STATUS_NORMAL) {
					//                        continue;
					//                    }
					$updateData[$goods[0]]['goodsId'] = $goodsInfo['goods_id'];
					$updateData[$goods[0]]['shopId'] = $goodsInfo['shop_id'];
					$updateData[$goods[0]]['specification_id'] = isset($goodsspecification['specification_id']) ?: 0;
					$updateData[$goods[0]]['num'] = $goods[1];
					$updateData[$goods[0]]['updateTime'] = time();
				}
			}
		}
		if ($updateData) {
			$updateData = array_values($updateData);
		}
		if ($userCartInfo = self::model('user_cart')->getOne('uid=?', $this->user_info['uid'])) {
			self::model('user_cart')->update([
				'content' => json_encode($updateData, 320),
				'update_time' => time(),
			], 'uid=?', $userCartInfo['uid']);
		} else {
			self::model('user_cart')->insert([
				'uid' => $this->user_info['uid'],
				'content' => json_encode($updateData, 320),
				'add_time' => time(),
				'update_time' => time(),
			]);
		}
		Response::ajax(200, '设置成功');
	}

	public function addAction() {
        if ($user_info = self::model('user')->checkLogin()) {
            $dealer_id = self::model('dealer')->dealerInfo($user_info['uid']);
            if ($dealer_id == -1) {
                Response::ajax(ADDRESS_ERROR, "请先填写收货地址！");
            }
            if ($dealer_id == -2) {
                Response::ajax(ADDRESS_ERROR, "您收货地址暂不是经营城市！");
            }
        }
		$goodsData = Request::getParams('goodsData');
		$goodsData = explode(';', $goodsData);

		self::model('user_rebate')->addRebate($this->user_info['uid']);

		$updateData = [];
		if ($goodsData) {
			foreach ($goodsData as $goods) {
				$goods = explode(':', $goods);
				if (isset($goods[2]) && isset($goods[0]) && isset($goods[1]) &&
					is_numeric($goods[0]) && is_numeric($goods[1]) && is_numeric($goods[2])) {
					if (!$goodsInfo = self::model('goods')->getOne('goods_id=?', $goods[0])) {
						continue;
					}
					if (!$goodsspecification = self::model('goods_specification')->getOne('specification_id=?', $goods[1])) {
					}
					$updateData[$goods[1]]['goodsId'] = $goodsInfo['goods_id'];
					$updateData[$goods[1]]['shopId'] = $goodsInfo['shop_id'];
					$updateData[$goods[1]]['specification_id'] = isset($goodsspecification['specification_id']) ? $goodsspecification['specification_id'] : 0;
					$updateData[$goods[1]]['num'] = $goods[2];
					$updateData[$goods[1]]['updateTime'] = time();
				}
			}
		}
		if (!$updateData) {
			Response::ajax(NORMAL_ERROR, '您提交的商品有误,添加失败');
		}
		if ($userCartInfo = self::model('user_cart')->getOne('uid=?', $this->user_info['uid'])) {
			$userGoodsInfo = self::model('user_cart')->getUserGoods($userCartInfo);
			$userCartDataWithIndex = self::model('user_cart')->buildCart($userGoodsInfo);
			if ($userCartDataWithIndex) {
				foreach ($updateData as $goodsIndex => $updateGoodsInfo) {
					if (isset($userCartDataWithIndex[$goodsIndex])) {
						$updateData[$goodsIndex]['num'] = $userCartDataWithIndex[$goodsIndex]['num'] + $updateGoodsInfo['num'];
						$updateData[$goodsIndex]['updateTime'] = time();
					}
				}
				foreach ($userCartDataWithIndex as $goodsIndex => $updateGoodsInfo) {
					if (!isset($updateData[$goodsIndex])) {
						$updateData[$goodsIndex] = $updateGoodsInfo;
					}
				}
			}
			$updateData = array_values($updateData);
			self::model('user_cart')->update([
				'content' => json_encode($updateData, 320),
				'update_time' => time(),
			], 'uid=?', $userCartInfo['uid']);
		} else {
			$updateData = array_values($updateData);
			self::model('user_cart')->insert([
				'uid' => $this->user_info['uid'],
				'content' => json_encode($updateData),
				'add_time' => time(),
				'update_time' => time(),
			]);
		}
		Response::ajax(200, '添加成功');
	}

	public function reduceAction() {
		$goodsData = Request::getParams('goodsData');
		$goodsData = explode(';', $goodsData);
		$updateData = [];
		if ($goodsData) {
			foreach ($goodsData as $goods) {
				$goods = explode(':', $goods);
				if (isset($goods[2]) && isset($goods[0]) && isset($goods[1]) &&
					is_numeric($goods[0]) && is_numeric($goods[1]) && is_numeric($goods[2])) {
					if (!$goodsInfo = self::model('goods')->getOne('goods_id=?', $goods[0])) {
						continue;
					}
					if (!$goodsspecification = self::model('goods_specification')->getOne('specification_id=?', $goods[1])) {
						continue;
					}
					$updateData[$goods[1]]['goodsId'] = $goodsInfo['goods_id'];
					$updateData[$goods[1]]['shopId'] = $goodsInfo['shop_id'];
					$updateData[$goods[1]]['specification_id'] = $goodsspecification['specification_id'];
					$updateData[$goods[1]]['num'] = $goods[2];
					$updateData[$goods[1]]['updateTime'] = time();
				}
			}
		}
		if (!$updateData) {
			Response::ajax(NORMAL_ERROR, '您提交的商品有误,减少失败');
		}
		if ($userCartInfo = self::model('user_cart')->getOne('uid=?', $this->user_info['uid'])) {
			$userGoodsInfo = self::model('user_cart')->getUserGoods($userCartInfo);
			$userCartDataWithIndex = self::model('user_cart')->buildCart($userGoodsInfo);
			if ($userCartDataWithIndex) {
				foreach ($userCartDataWithIndex as $goodsIndex => $cartGoodsInfo) {
					if (isset($updateData[$goodsIndex])) {
						$num = $cartGoodsInfo['num'] - $updateData[$goodsIndex]['num'];
						if ($num <= 0) {
							unset($userCartDataWithIndex[$goodsIndex]);
						} else {
							$userCartDataWithIndex[$goodsIndex]['num'] = $num;
							$userCartDataWithIndex[$goodsIndex]['updateTime'] = time();
						}
					}
				}
//                foreach ($updateData as $goodsIndex=>$updateGoodsInfo) {
				//                    if(($userCartDataWithIndex[$goodsId]['num']-$updateGoodsInfo['num'])<0) {
				//                        unset($updateData[$goodsIndex]);
				//                    }else{
				//                       $updateData[$goodsIndex]['num'] = $userCartDataWithIndex[$goodsId]['num']-$updateGoodsInfo['num'];
				//                       $updateData[$goodsIndex]['updateTime'] = time();
				//                    }
				//                }
			}
			$updateData = array_values($userCartDataWithIndex);
			self::model('user_cart')->update([
				'content' => json_encode($updateData, 320),
				'update_time' => time(),
			], 'uid=?', $userCartInfo['uid']);
		}
		Response::ajax(200, '减少成功');
	}

	public function deleteAction() {
		$specification_id = Request::getParams('specification_id');
		if ($userCartInfo = self::model('user_cart')->getOne('uid=?', $this->user_info['uid'])) {
			$userGoodsInfo = self::model('user_cart')->getUserGoods($userCartInfo);
			if ($userGoodsInfo) {
				foreach ($userGoodsInfo as $index => $goodsInfo) {
					if ($goodsInfo['specification_id'] == $specification_id) {
						unset($userGoodsInfo[$index]);
					}
				}
			}
			if ($userGoodsInfo) {
				$userGoodsInfo = array_values($userGoodsInfo);
			} else {
				$userGoodsInfo = [];
			}
			self::model('user_cart')->update([
				'content' => json_encode($userGoodsInfo, 320),
				'update_time' => time(),
			], 'uid=?', $userCartInfo['uid']);
			Response::ajax(200, '删除成功');
		} else {
			Response::ajax(NORMAL_ERROR, '您的购物车不存在该商品');
		}
	}

	public function clearAction() {
		if ($userCartInfo = self::model('user_cart')->getOne('uid=?', $this->user_info['uid'])) {
			$userGoodsInfo = [];
			self::model('user_cart')->update([
				'content' => json_encode($userGoodsInfo, 320),
				'update_time' => time(),
			], 'uid=?', $userCartInfo['uid']);
		}
		Response::ajax(200, '清除成功');
	}

	public function listAction() {
        $postage=0;
        $dealer_id=self::model('dealer')->isDefault();
        if ($user_info = self::model('user')->checkLogin()) {
            $dealer_id=self::model('dealer')->dealerInfo($user_info['uid']);
            if($dealer_id==-1){
                Response::ajax(ADDRESS_ERROR, "请先填写收货地址！");
            }
            if($dealer_id==-2){
                Response::ajax(ADDRESS_ERROR, "您收货地址暂不是经营城市！");
            }
            if($dealer_id==0){
                $postage=1;
                $dealer_id=self::model('dealer')->isDefault();
            }
        }

		$list = [
			'totalNum' => 0,
			'totalPrice' => 0,
			'totalPostage' => 0,
			'list' => [],
		];
		if ($userCartInfo = self::model('user_cart')->getOne('uid=?', $this->user_info['uid'])) {
			$userGoodsInfo = self::model('user_cart')->getUserGoods($userCartInfo);
			$goodsIds = $goodsData = $shopIds = $shopData = [];
			if (!$userGoodsInfo) {
				Response::ajax(200, 'success', $list);
			}
			foreach ($userGoodsInfo as $goodsInfo) {
				if ($goodsInfo['specification_id']) {
					$goodsIds[] = $goodsInfo['specification_id'];
				}
				$shopIds[] = $goodsInfo['shopId'];
			}
			$goodsIds = implode(',', $goodsIds);
			$shopIds = implode(',', $shopIds);
			$goodsList = self::model('goods')->query("select a.name,a.image,a.status,a.shop_id,b.specification_id,b.goods_id,b.attributes_id1,b.attributes_id2,b.sales_price,b.sale_total,b.stock_total,a.postage from wf_goods a,wf_goods_specification b where a.goods_id=b.goods_id and b.specification_id in ({$goodsIds})")->fetchAll();
			$shopList = self::model('shop')->query("select * from wf_shop where shop_id in ({$shopIds})")->fetchAll();
			if (!$goodsList || !$shopList) {
				Response::ajax(200, 'success', $list);
			}
			foreach ($shopList as $shopInfo) {
				$shopData[$shopInfo['shop_id']] = $shopInfo;
			}
			$specificationIds1 = [];
			$specificationIds2 = [];
			foreach ($goodsList as $goodsInfo) {
				$goodsData[$goodsInfo['specification_id']] = $goodsInfo;
				if ($goodsInfo['attributes_id1']) {
					$specificationIds1[] = intval($goodsInfo['attributes_id1']);
					$specificationIds2[] = intval($goodsInfo['attributes_id2']);
				}

			}
			$specificationIds = array_keys(array_flip($specificationIds1) + array_flip($specificationIds2));
			if ($specificationIds) {
				$specificationIds = implode(',', $specificationIds);
				$attribute = self::model('goods_attribute')->query("select attribute_id,name from wf_goods_attribute where attribute_id in ({$specificationIds})")->fetchAll();
				$attributearr = [];
				foreach ($attribute as $key => $value) {
					$attributearr[$value['attribute_id']] = $value['name'];
				}
			}
            $list['totalPostage']=0;
			foreach ($userGoodsInfo as $cartInfo) {
				if (!isset($goodsData[$cartInfo['specification_id']]) || !isset($shopData[$cartInfo['shopId']])) {
					continue;
				}
				$goodsInfo = $goodsData[$cartInfo['specification_id']];
				$shopInfo = $shopData[$goodsInfo['shop_id']];
				if (!isset($list['list'][$shopInfo['shop_id']])) {
					$list['list'][$shopInfo['shop_id']] = [
						'totalNum' => 0,
						'totalPrice' => 0,
						'totalPostage' => 0,
						'shopInfo' => [
							'shopId' => intval($shopInfo['shop_id']),
							'name' => strval($shopInfo['name']),
							'image' => strval($shopInfo['image']),
							'avatar' => strval($shopInfo['avatar']),
						],
						'goodsList' => [],
					];
				}
				if ($goodsInfo['attributes_id1'] && $goodsInfo['attributes_id2']) {
					$attributes1 = $attributearr[$goodsInfo['attributes_id1']];
					$attributes2 = $attributearr[$goodsInfo['attributes_id2']];
					$attributeName = $attributes1 . ' ' . $attributes2;
				} elseif ($goodsInfo['attributes_id1']) {
					$attributes1 = $attributearr[$goodsInfo['attributes_id1']];

					$attributeName = $attributes1;
				} else {
					$attributeName = "";
				}
                $discount=self::model('dealer_discount')->getOne(['goods_id=?','dealer_id=?','uid=?','specification_id=?','type=?','is_delete=?'],[$goodsInfo['goods_id'],$dealer_id,$user_info['uid'],$goodsInfo['attributes_id1'],1,0]);
                if($discount){
                    $goodsInfo['sales_price']=$discount['price'];
                }

                $list['list'][$shopInfo['shop_id']]['goodsList'][] = [
					'goodsId' => intval($goodsInfo['goods_id']),
					'num' => intval($cartInfo['num']),
					'saleTotal' => intval($goodsInfo['sale_total']),
					'stockTotal' => intval($goodsInfo['stock_total']),
					'specification_id' => intval($goodsInfo['specification_id']),
					'status' => intval($goodsInfo['status']),
					'name' => strval($goodsInfo['name']),
					'image' => strval($goodsInfo['image']),
					'price' => floatval($goodsInfo['sales_price']),
					'postage' =>$postage==0?0: floatval($goodsInfo['postage']),
					'attributeName' => $attributeName,
				];

				$num = min($goodsInfo['stock_total'], $cartInfo['num']);
				$list['list'][$shopInfo['shop_id']]['totalNum'] += $num;
				$list['list'][$shopInfo['shop_id']]['totalPrice'] += $num * $goodsInfo['sales_price'];
				$list['list'][$shopInfo['shop_id']]['totalPostage'] += $goodsInfo['postage'];

				$list['totalNum'] += $num;
				$list['totalPrice'] += $num * $goodsInfo['sales_price'];

				if($goodsInfo['postage']>=$list['totalPostage']&&$postage==1){
                    $list['totalPostage'] = $goodsInfo['postage'];
                }
                if($postage==0){
                    $list['totalPostage']=0;
                }
			}
			$list['totalPrice']=sprintf("%.2f",$list['totalPrice']);
			$list['list'] = array_values($list['list']);
		}
		Response::ajax(200, 'success', $list);
	}
}